<template>
  <div class="user-management">
    <!-- 子菜单导航 -->
    <div class="sub-menu-nav">
      <el-menu
        :default-active="activeTab"
        mode="horizontal"
        @select="handleTabSelect"
        class="sub-menu compact"
      >
        <el-menu-item index="users" class="compact-item">人员列表</el-menu-item>
        <el-menu-item index="permissions" class="compact-item">权限管理</el-menu-item>
      </el-menu>
    </div>

    <!-- 人员列表页面 -->
    <div v-if="activeTab === 'users'" class="content-section">
      <div class="page-header">
        <h2>人员列表</h2>
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          添加人员
        </el-button>
      </div>

      <el-table :data="userList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="role_name" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role_name)">{{ row.role_name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text @click="editUser(row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button type="danger" text @click="deleteUser(row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 权限管理页面 -->
    <div v-if="activeTab === 'permissions'" class="content-section">
      <div class="page-header">
        <h2>权限管理</h2>
      </div>

      <el-table :data="roleList" style="width: 100%">
        <el-table-column prop="name" label="角色" width="120" />
        <el-table-column label="菜单权限">
          <template #default="{ row }">
            <el-checkbox-group v-model="row.menu_permissions" @change="updatePermissions(row)">
              <el-checkbox label="monitor">监控中心</el-checkbox>
              <el-checkbox label="streams">直播流管理</el-checkbox>
              <el-checkbox label="tasks">任务管理</el-checkbox>
              <el-checkbox label="clips">拆条任务</el-checkbox>
              <el-checkbox label="records">录制管理</el-checkbox>
              <el-checkbox label="servers">集群管理</el-checkbox>
              <el-checkbox label="users">人员管理</el-checkbox>
              <el-checkbox label="storage">存储管理</el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="!!editingUser.value" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="密码" v-if="!editingUser.value">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userForm.role_id" placeholder="请选择角色">
            <el-option 
              v-for="role in roleList" 
              :key="role.id" 
              :label="role.name" 
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="userForm.is_active"
            :active-value="true"
            :inactive-value="false"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'

const activeTab = ref('users')
const loading = ref(false)
const showAddDialog = ref(false)
const editingUser = ref(null)

const userList = ref([])
const roleList = ref([])

const userForm = reactive({
  username: '',
  name: '',
  role_id: null,
  is_active: true
})

const menuPermissions = reactive({})
const availableMenus = [
  { key: 'monitor', label: '监控中心' },
  { key: 'streams', label: '直播流管理' },
  { key: 'tasks', label: '任务管理' },
  { key: 'clips', label: '拆条任务' },
  { key: 'records', label: '录制管理' },
  { key: 'servers', label: '集群管理' },
  { key: 'users', label: '人员管理' },
  { key: 'storage', label: '存储管理' }
]

const handleTabSelect = (tab) => {
  activeTab.value = tab
}

const getRoleType = (roleName) => {
  const map = {
    '超级管理员': 'danger',
    '管理员': 'warning',
    '操作员': 'primary',
    '访客': 'info'
  }
  return map[roleName] || 'info'
}

const getRoleName = (roleId) => {
  const role = roleList.value.find(r => r.id === roleId)
  return role ? role.name : '未知角色'
}

const editUser = (user) => {
  editingUser.value = user
  Object.assign(userForm, {
    username: user.username,
    name: user.name,
    role_id: user.role_id,
    is_active: user.is_active
  })
  showAddDialog.value = true
}

const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(`确认删除用户 ${user.username} 吗？`, '提示', {
      type: 'warning'
    })
    await userApi.deleteUser(user.id)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除用户失败:', error)
    }
  }
}

const saveUser = async () => {
  try {
    const data = {
      username: userForm.username,
      name: userForm.name,
      role_id: userForm.role_id,
      is_active: userForm.is_active
    }

    if (editingUser.value) {
      // 更新用户时不传密码
      await userApi.updateUser(editingUser.value.id, data)
      ElMessage.success('更新成功')
    } else {
      // 新增用户需要密码
      if (!userForm.password) {
        ElMessage.error('请设置用户密码')
        return
      }
      data.password = userForm.password
      await userApi.createUser(data)
      ElMessage.success('添加成功')
    }
    
    showAddDialog.value = false
    editingUser.value = null
    resetForm()
    fetchUsers()
  } catch (error) {
    ElMessage.error(editingUser.value ? '更新失败' : '添加失败')
    console.error('保存用户失败:', error)
  }
}

const resetForm = () => {
  Object.assign(userForm, {
    username: '',
    name: '',
    password: '',
    role_id: null,
    is_active: true
  })
}

const fetchUsers = async () => {
  try {
    loading.value = true
    console.log('=== 开始获取用户列表 ===')
    const response = await userApi.getUsers()
    console.log('用户列表原始响应:', response)
    
    let users = []
    if (response && response.items) {
      users = Array.isArray(response.items) ? response.items : []
    } else if (Array.isArray(response)) {
      users = response
    }
    
    console.log('解析后的用户数组:', users)
    console.log('用户数量:', users.length)
    userList.value = users
    
    if (users.length === 0) {
      console.warn('⚠️ 用户列表为空！')
    }
  } catch (error) {
    console.error('❌ 获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const fetchRoles = async () => {
  try {
    console.log('=== 开始获取角色列表 ===')
    const response = await userApi.getRoles()
    console.log('角色列表原始响应:', response)
    
    let roles = []
    if (response && response.items) {
      roles = Array.isArray(response.items) ? response.items : []
    } else if (Array.isArray(response)) {
      roles = response
    }
    
    console.log('解析后的角色数组:', roles)
    console.log('角色数量:', roles.length)
    roleList.value = roles
    
    if (roles.length === 0) {
      console.warn('⚠️ 角色列表为空！')
    }
    
    roles.forEach(role => {
      menuPermissions[role.name] = role.menu_permissions || []
    })
    console.log('角色权限映射:', menuPermissions)
  } catch (error) {
    console.error('❌ 获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

const updatePermissions = async (role) => {
  try {
    await userApi.updateRole(role.id, {
      name: role.name,
      menu_permissions: role.menu_permissions,
      is_active: role.is_active
    })
    ElMessage.success(`已更新 ${role.name} 的权限设置`)
  } catch (error) {
    ElMessage.error('权限更新失败')
    console.error('权限更新失败:', error)
  }
}

onMounted(() => {
  fetchUsers()
  fetchRoles()
})
</script>

<style scoped>
.user-management {
  padding: 0;
}

.sub-menu-nav {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.sub-menu.compact {
  border: none;
  background: transparent;
  height: 48px;
}

:deep(.sub-menu.compact .el-menu-item) {
  height: 48px;
  line-height: 48px;
  padding: 0 20px;
  font-size: 14px;
}

:deep(.sub-menu.compact .el-menu-item.is-active) {
  background-color: #f0f2f5;
  border-bottom: 2px solid #3b82f6;
  color: #3b82f6;
}

:deep(.sub-menu.compact .el-menu-item:hover) {
  background-color: #f9fafb;
  color: #3b82f6;
}

.content-section {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 500;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

:deep(.el-checkbox) {
  margin-right: 0;
}
</style>